#!/bin/bash
# set -e
# set -x
#trap 'echo "Error at line $LINENO: $BASH_COMMAND"; exit 1' ERR

# Branch命名检查
# 获取当前Branch的名称
JenkinsBranchName=$1
if [ -n "$JenkinsBranchName" ]; then
  CURRENT_BRANCH="${JenkinsBranchName}" # Jenkins获取分支名
else
  CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD) # 本地获取分支名
fi
echo "当前分支名称: $CURRENT_BRANCH"

# 检查是否成功获取Branch名称
if [ -z "$CURRENT_BRANCH" ]; then
  echo "错误：无法获取当前Branch名称。请确保在Git仓库中运行此脚本。"
  exit 1
fi

# 定义Branch命名规范的正则表达式
# 获取公共配置PATTERN
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/config.sh"

# 校验分支名称
if ! echo "$CURRENT_BRANCH" | grep -Pq "$PATTERN"; then

  arr=(
    "(1)feat/215-用户登录界面;"
    "(2)hotfix/284-修复用户名重复问题;   "
    "(3)bugfix/233-修复404问题;   "
    "(4)release/v1.0.0;|release/20250516;    "
    "(5)master;   "
    "(5)dev")

  # 使用分号连接
  joined=$(IFS=';' echo "${arr[*]}")

  echo "分支名称 '$CURRENT_BRANCH' 不符合命名规范。命名规则:[issue_type]/[issue_id]-description, 请使用以下命名规范之一：$joined"

  exit 1
fi

# 注意这里加了 || true
files=$(git diff --cached --name-only --diff-filter=AM | grep -E '\.(ts|tsx|vue)$' || true)

if [ -z "$files" ]; then
  exit 0
fi

set +e
output=$(echo "$files" | xargs -r npx eslint 2>&1)
exit_code=$?

if [ $exit_code -ne 0 ]; then
  echo "ESLint 检查未通过，请修复后再提交！"
  echo "$output"
  exit $exit_code
fi
